package com.minimalist.common.config.bucket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;

/**
 * @author 11987
 */
@Component
public class SystemMetricsCollector{

    private static final Logger log = LoggerFactory.getLogger(SystemMetricsCollector.class);
    private final OperatingSystemMXBean osBean;

    public SystemMetricsCollector(){
        this.osBean = ManagementFactory.getOperatingSystemMXBean();
    }

    public SystemMetrics collectMetrics(){
        double cpuLoad = getProcessCpuLoad();
        long freeMemory = Runtime.getRuntime().freeMemory();
        long totalMemory = Runtime.getRuntime().totalMemory();
        double memoryUsage = 1.0 - (double) freeMemory / totalMemory;

        return new SystemMetrics(cpuLoad, memoryUsage);
    }

    private double getProcessCpuLoad(){
        if (osBean instanceof com.sun.management.OperatingSystemMXBean){
            return ((com.sun.management.OperatingSystemMXBean) osBean).getCpuLoad();
        }
        return osBean.getSystemLoadAverage();
    }
}
